
# INTENSITY.TCL

source bin/xsmack-lib.tcl

if { [ llength $argv ] < 1 } {
    puts "Need N!"
    exit 1
}

set N $argv
if { $N < 2 } {
    puts "N must be > 1"
    exit 1
}

set result_files [ glob users/justin/plans/result*.data ]

proc to_secs { date } {
    return [ clock scan $date -format "%Y-%m-%d" ]
}

proc to_date { secs } {
    set secs [ expr round($secs) ]
    # show secs
    return [ clock format $secs -format "%Y-%m-%d" ]
}


set start "2013-01-01"
set timestamp_start [ to_secs $start ]

set dates {}
array set T {}

set i 1
foreach f $result_files {
    regexp ".*result-(.*).data" $f x date
    lappend dates $date
}

# set dates { 2013-02-01 2013-03-01 2013-04-01 2013-05-01 2013-06-01
#     2013-02-06 2013-03-06 2013-04-06 2013-05-06 2013-06-06
#     2013-04-26 2013-03-30 }

set dates [ lsort $dates ]
foreach date $dates {
    # show date
    set t [ to_secs $date ]
    set T($i) $t
    # show T($i)
    incr i
}

set timestamp_stop [ clock seconds ]
# set timestamp_stop [ to_secs "2013-06-02" ]

# Two weeks before and after, inclusive
set window [ expr 24*60*60 * 7  ]

set total [ expr $timestamp_stop - $timestamp_start ]
set slice [ expr double($total) / ($N-1) ]

set p 1
set q 1
set x $timestamp_start
for { set i 0 } { $i < $N } { incr i } {
    # show x
    # puts "x: [ to_date $x ]"
    set z0 [ expr $x - $window ]
    # show z0
    # puts "z0: [ to_date $z0 ]"
    # Increment p
    while { true } {
        set p1 [ expr $p + 1 ]
        if { $T($p1) > $z0 } break
        incr p
    }
    # show p
    # puts "p: [ to_date $T($p) ]"
    # puts ok
    # Increment q
    set z1 [ expr $x + $window ]
    while { true } {
        if { $T($q) > $z1 } break
        set q1 [ expr $q + 1 ]
        if { ! [ info exists T($q1) ] } break
        incr q
    }
    # show q
    # puts "q: [ to_date $T($q) ]"

    set points [ expr $q - $p - 1 ]
    if { $x     - $T($p) < $window } {
        incr points
        # puts "up 1"
    }
    if { $T($q) - $x     < $window } {
        incr points
        # puts "up 2"
    }

    printf "%0.0f %0.2f" [ expr $x * 1000 ] [ expr double($points) / 2 ]

    set x [ expr $x + $slice ]
}
